from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models import Goods
from app.models.mini import MiniFav
from app.schemas.mini import MiniFavCreate,MiniFavUpdate


class MiniFavController(CRUDBase[MiniFav, MiniFavCreate, MiniFavUpdate]):
    def __init__(self):
        super().__init__(model=MiniFav)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        goods_ids = {goods['type_id'] for goods in data}  # 获取所有的 goods_id
        goods = await Goods.filter(id__in=goods_ids)
        goods_dict = {good.id: good.cover for good in goods}
        goods_name_dict = {good.id: good.name for good in goods}
        for item in data:
            item["goods_name"] = goods_name_dict.get(item['type_id'], "已删除商品")
            item["goods_cover"] = goods_dict.get(item['type_id'], "已删除商品")
        return total, data

    async def do_create(self, obj_in: MiniFavCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: MiniFavUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, search: Q = Q()):
        await self.remove_q(search)
        return True

mini_fav_controller = MiniFavController()
